#!/usr/bin/python
# Distributed under the terms of the GNU General Public License v2
# $Header: $

import sys

if len(sys.argv) < 2:
	print "Usage: tbz2ipkg </path/package.tbz2>"
	sys.exit(1)

import os, xpak, string, socket

os.umask(0022)

# If we are not using this tool from a gentoo system it should still
# function, so we only want to import portage system unless we are indeed
# a gentoo system.

if os.path.exists("/etc/gentoo-release"):
	vendor = "Gentoo"
	import portage
else:
	vendor = "Generic"

if not os.path.exists(sys.argv[1]):
	print "File: "+tbz2ball+" does not appear to exist."
	sys.exit(1)

tbz2ball = os.path.realpath(sys.argv[1])
use=[]; iuse=[];
priority = "optional";
licence="";
depend="";
desc=os.path.basename(tbz2ball)+"\n";
arch="Unknown\n";

tmpdir = "/var/tmp/portage/ipkg/"
if not os.path.exists(tmpdir):
	os.mkdir(tmpdir)
tmpdir += os.path.basename(tbz2ball)+"/"

tbz2file = xpak.tbz2(tbz2ball)

ipkg = tmpdir+"/package.ipk"

keys = tbz2file.filelist()

if not os.path.exists(tmpdir):
	os.mkdir(tmpdir)

if not os.path.exists(tmpdir+"/data/"):
	os.mkdir(tmpdir+"/data/")

# open the control file and print mapping values.
control_file = tmpdir+"control"

if os.path.exists(control_file):
	os.unlink(control_file)

for key in keys:
	val = " ".join(tbz2file.getfile(key).split())

	if val != "":
		if key == "CHOST":
			chost = val
		if key == "CFLAGS":
			cflags = val
		if key == "PF":
			package = val
		if key == "PV":
			version = val
		if key == "RDEPEND":
			depend = val;
		if key == "ARCH":
			arch = val
		if key == "CATEGORY":
			section = val
		if key == "LICENSE":
			licence = val

		if key == "environment.bz2":
			val = tbz2file.getfile(key)
			fp=open(tmpdir+key, "wb")
			fp.write(tbz2file.getfile(key))
			fp.flush()
			fp.close()

			os.system("bzcat "+ tmpdir + key +" > "+tmpdir+"/env")

			# FIXME: use native API and get this in a buffer.
			os.system("grep ^ARCH= "+tmpdir+"/env | cut -d = -f 2 > "+tmpdir+"/arch")
			os.system("grep ^DESCRIPTION= "+tmpdir+"/env | awk -F = '{print $2}' >"+tmpdir+"/desc")

			fp = open(tmpdir+"/arch", "rb")
			arch = fp.read()
			fp.close()

			fp = open(tmpdir+"/desc", "rb")
			desc = fp.read()
			fp.close()

			os.unlink(tmpdir+"/desc")
			os.unlink(tmpdir+"/arch")
			os.unlink(tmpdir+key)
			val = ""

		if key == "USE":
			use = string.split(val, " ")
		if key == "IUSE":
			iuse = string.split(val, " ")
		# actually we might not want to map unknowns.
		#if val != "":
		#	sys.stdout.write(key+": "+val + "\n")

# Open the control file and write to it.
fp = open(control_file, "w")
fp.write("Package: " + package + "\n")
fp.write("Architecture: " + arch )
fp.write("Description: " + desc )
fp.write("Licence: " + licence + "\n")
fp.write("Vendor: " + vendor + "\n")
fp.write("Depend: " + depend + "\n")
fp.write("Iuse: " +string.join(iuse) +"\n")
fp.write("Use: " + string.join(use) + "\n")

if os.environ['USER']:
	fp.write("Maintainer: " +os.environ['USER'] + "@"+socket.gethostname()+"\n")

# map IUSE->USE and look for build flag set in both. 
# if set then we change the package priority from optional to required.
for x in iuse:
	for y in use:
		if x == y:
			if x == "build":
				priority = "required"
				# break

fp.write("Priority: " + priority + "\n")
fp.write("#CHOST: " + chost + "\n")
fp.write("#CFLAGS: " + cflags + "\n")
fp.flush()
fp.close()

ret = os.system("/bin/tar -jxpf "+ tbz2ball + " -C" + tmpdir+"/data/ 2>/dev/null || :")

if vendor == "Gentoo":
	for x in ['doc', 'info', 'man', 'html', 'sgml']:
		if "no"+x in portage.features:
			ret = os.system("/bin/rm -rf "+tmpdir+"/data/usr/share/"+x)

# really need to find . -name '*.a' | xargs rm -rf
for x in ['/usr/include', '/usr/lib/*.a', '/usr/lib/*.la']:
	#print "/bin/rm -rf "+tmpdir+"/data/"+x
	ret = os.system("/bin/rm -rf "+tmpdir+"/data/"+x)

# touch out target
#fp = open(ipkg, "w")
#os.chmod(ipkg, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP)
#fp.close()

print ">>> Building ipkg..."

os.chdir(tmpdir)
if os.path.exists("./control.tar.gz"):
	os.unlink("./control.tar.gz")
ret = os.system("tar zcf ./control.tar.gz ./control")

os.chdir(tmpdir+"/data/")
ret = os.system("/bin/tar -zcpf ../data.tar.gz ./")
ret = os.system("/bin/rm -rf "+tmpdir+"/data/")

os.chdir(tmpdir)
os.system("tar -zcf "+ipkg+" ./control.tar.gz ./data.tar.gz ./env")
os.system("mv "+ipkg+" `dirname "+tbz2ball+"`/`basename $PWD .tbz2`.ipk")
os.unlink("./control.tar.gz")
os.unlink("./env")
os.unlink("./data.tar.gz")
if os.path.exists(control_file):
	os.unlink(control_file)

sys.exit(0)
